package com.example.takeaway.controller;

import com.auth0.jwt.JWT;
import com.example.takeaway.entity.User;
import com.example.takeaway.entity.VO.LoginUser;
import com.example.takeaway.serivce.IUserService;
import com.example.takeaway.utils.PassToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

import com.example.takeaway.utils.JWTUtils;
import com.example.takeaway.utils.ServerResponse;
@RestController
public class LoginController {

        @Autowired
        IUserService userService;
        @Autowired
        RedisTemplate<String,Object> redisTemplate;
        @PassToken
        @PostMapping("/login")
        public ServerResponse<String> login(@RequestBody LoginUser loginUser){

            String storeCode=(String) redisTemplate.opsForValue().get("captcha_codes:"+loginUser.getUuid());
            System.out.println(storeCode+loginUser.toString());
            System.out.println(loginUser.toString());
            if (loginUser.getCode().equals(storeCode)){
                User u=userService.getuser(loginUser);
                if(u!=null){
                    Map<String,String> map=new HashMap<>();
                    map.put("userid",u.getUserid()+"");
                    map.put("username",u.getUsername());
                    map.put("role",u.getRole());
                    String token= JWTUtils.getToken(map);
                    redisTemplate.delete(storeCode);
                    return ServerResponse.createBysuccess(200,token,"登录成功");
                }
                return ServerResponse.createBysuccess(500,"","账号或密码错误");
            }else {
                return ServerResponse.createBysuccess(500,"","验证码错误");
            }
        }
        @GetMapping("/getInfo")
        public ServerResponse<User> getInfo(HttpServletRequest request){
            String token =request.getHeader("Authorization");
            System.out.println(token+" ");
            String id= JWT.decode(token.substring(token.lastIndexOf(" ")+1)).getClaim("userid").asString();
            User user=userService.getuserById(Integer.parseInt(id));
            return ServerResponse.createBysuccess(200,user,"查询成功");
        }
    }


